# -*- coding: utf-8 -*-
import json
import logging

from django.conf import settings
from api.preset.handler import get_fixed_bucket
from api.show.model import ShowLite
from common.account.db.account import get_account
from common.show.db import get_user_shows, get_show_by_id, get_verfied_shows
from common.show.model import SHOW_STATUS
from common.utils.api import page2offset
from common.utils.exceptions import AuthenticateError
from common.utils.tz import ts_to_local_datetime_str

_LOGGER = logging.getLogger('bigbang')

_DEFAULT_PAGE_SIZE = 20


def view_my_shows(user_id, page, size):
    limit, offset = page2offset(page, size, max_size=30, default_size=20)
    if not page or page < 1:
        page = 1
    show_list = get_user_shows(user_id, limit, offset)
    show_lites = []
    for show in show_list:
        show_lites.append(_create_show_lite(show))
    return show_lites


def view_shows_timeline(page, size):
    limit, offset = page2offset(page, size, max_size=30, default_size=20)
    shows = get_verfied_shows(limit, offset)
    show_lites = [_create_show_lite(show) for show in shows]
    return show_lites


def _create_show_lite(show):
    account = get_account(show.user_id)
    show_lite = ShowLite()
    show_lite.id = show.id
    show_lite.order_id = show.order_id
    show_lite.user_name = account.user_name[0] + '***' + account.user_name[-1]
    show_lite.avatar = get_fixed_bucket(account.avatar, bucket='avatar') if account.avatar else settings.DEFAULT_AVATAR
    show_lite.term = show.term_number
    show_lite.activity_type = show.activity_type
    show_lite.content = show.content
    show_lite.status = show.status
    show_lite.verify_at = ts_to_local_datetime_str(show.verified_at) if show.verified_at else None
    show_lite.highlight = show.highlight
    show_lite.verify_comment = show.verify_comment
    show_lite.images = get_fixed_bucket(show.images, bucket='show').split(',') if show.images else []
    watermark_flag = True if show.status == SHOW_STATUS.VERIFY_SUCCESS else False
    show_lite.small_images = thum(show_lite.images)
    show_lite.images = add_watermark(show_lite.images, watermark_flag)

    detail = json.loads(show.detail)
    show_lite.win_price = float(detail['win_price']) + float(detail['bonus'])
    show_lite.price = float(detail['price'])
    show_lite.bet_type = float(detail['bet_type'])

    return show_lite


def thum(images):
    images = [image + '-thum' for image in images]
    return images


def add_watermark(images, watermark_flag):
    if watermark_flag:
        images = [image + '-watermark' for image in images]
    return images


def view_show_detail(user_id, show_id, src):
    show = get_show_by_id(show_id)
    if show.status != SHOW_STATUS.VERIFY_SUCCESS and show.user_id != user_id:
        raise AuthenticateError('not access')
    return _create_show_lite(show)
